<?php
namespace App\Logic\Stocking;

use App\Models\Basics\SysICountry;
use App\Models\Basics\Transport;
use App\Models\SsBasic\AreaSku;
use App\Models\Stocking\StockingSetDate;
use Illuminate\Support\Facades\DB;
class InitSetDate
{
    /**
     * 设定：每天运行
     */
    public static function exe(){
        $country = [];
        $pCycle = [];
        $seaDayArr = [];
        StockingSetDate::query()->orderBy('id')
            ->chunk(50, function ($ss) use (&$country,&$pCycle,&$seaDayArr){
                try{
                    DB::beginTransaction();
                    foreach ($ss as $_ss){
                        if(!array_key_exists($_ss->area_id,$country)){
                            $country[$_ss->area_id] = SysICountry::getCountryIdsByAreaId($_ss->area_id);
                        }
                        $countryIds = $country[$_ss->area_id];
                        $key = $_ss->area_id.'_'.$_ss->classify_id;
                        if(!array_key_exists($key,$pCycle)){
                            $pCycle[$key] = StockingSetDate::getPCycle($countryIds,$_ss->classify_id);
                        }
                        if(!array_key_exists($_ss->area_id,$seaDayArr)){
                            $seaDayArr[$_ss->area_id] = Transport::getShipmentDay($_ss->area_id,1);
                        }
                        $seaAvailable = AreaSku::getAvailable($pCycle[$key],$seaDayArr[$_ss->area_id]);
                        $_ss->purchase_cycle = $pCycle[$key];
                        $_ss->sea_day = $seaDayArr[$_ss->area_id];
                        $_ss->sea_available = $seaAvailable;
                        $_ss->status = StockingSetDate::setDateLe2Date($_ss->set_date,$seaAvailable);
                        $_ss->save();
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }
}
